/**
 * 作者：yhb
 * 时间：2011-2-17 10:24:21
 * 对象功能：权限的辅助类。
 * */
package com.towker.frame.share.rbac.res;

import java.util.*;

import com.towker.core.util.BeanUtils;
import com.towker.frame.model.rbac.Resource;
import com.towker.frame.service.cache.IPermissionCache;
import com.towker.frame.service.rbac.res.ResourceService;

public class PermissionShare{
	private IPermissionCache permissionCache;
	
	public void setIPermissionCache(IPermissionCache cache)
	{
		permissionCache=cache;
	}
	
	public boolean isResIdPermission(long userid,long sysid,String resId)
	{
		ResourceService service=(ResourceService)BeanUtils.getBean(ResourceService.class);
		List<Resource> userRes=permissionCache.getUserPermissionCache(userid+"");
		if(null==userRes||0==userRes.size()){
			userRes=service.getUserPermission(userid, sysid);
			permissionCache.addUserPermissionCache(userid+"", userRes);
		}
		for(Resource tmp:userRes)if(resId.equals(tmp.getAlias()))return true;
		List<Resource> sysRes=permissionCache.getSysPermissionCache(sysid+"");
		if(null==sysRes||0==sysRes.size()){
			sysRes=service.getResBySysid(sysid);
			permissionCache.addSysPermissionCache(sysid+"", sysRes);
		}
		for(Resource tmp:sysRes)if(resId.equals(tmp.getAlias()))return false;
		return true;
	}
	
	/**url是否具有权限*/
	public  boolean isPermission(long userid,long sysid,String url)
	{
		ResourceService service=(ResourceService)BeanUtils.getBean(ResourceService.class);
		List<Resource> userRes=permissionCache.getUserPermissionCache(userid+"");
		if(null==userRes||0==userRes.size()){
			userRes=service.getUserPermission(userid, sysid);
			permissionCache.addUserPermissionCache(userid+"", userRes);
		}
		for(Resource tmp:userRes)if(url.equals(tmp.getUrl()))return true;
		List<Resource> sysRes=permissionCache.getSysPermissionCache(sysid+"");
		if(null==sysRes||0==sysRes.size()){
			sysRes=service.getResBySysid(sysid);
			permissionCache.addSysPermissionCache(sysid+"", sysRes);
		}
		for(Resource tmp:sysRes)if(url.equals(tmp.getUrl()))return false;
		return true;
	}
	/**清除用户权限缓存*/
	public void removeUserPermissionCache(String userid){
		permissionCache.removeUserPermissionCache(userid);
	}
	/**清除系统权限缓存*/
	public void removeSysPermissionCache(String sysid){
		permissionCache.removeSysPermisssionCache(sysid);
	}
}
